package com.google.coffeeshop.gui.desktop;

import java.awt.BorderLayout;
import java.awt.CardLayout;

import javax.swing.ImageIcon;
import javax.swing.JLabel;
import javax.swing.JPanel;

import com.google.coffeeshop.gui.desktop.message.CaptionMessages;

public class AppFrame extends AbstractBaseFrame {
	private static final long serialVersionUID = 1L;

	private static LoginPanel loginPanel;
	private static MainPanel mainPanel;
	
	private JPanel pnlContent;
	private JPanel pnlTitle;
	
	public AppFrame() {
		super(CaptionMessages.LOGIN_TITLE);
		super.setSize(472, 354);
		this.getContentPane().setLayout(new BorderLayout(0, 0));

		JLabel lblLoginTittle = SwingFactory.createTitleLabel("Login to Application");
		lblLoginTittle.setIcon(new ImageIcon(AppFrame.class.getResource("/com/google/coffeeshop/gui/desktop/images/logo.png")));
		
		pnlTitle = new JPanel(new CardLayout(0, 0));
		pnlTitle.add(lblLoginTittle, LOGIN_VIEW);
		getContentPane().add(pnlTitle, BorderLayout.NORTH);
		
		pnlContent = new JPanel(new CardLayout(0, 0));
		pnlContent.add(getLoginPanel(this), LOGIN_VIEW);
		pnlContent.add(getMainPanel(this), MAIN_VIEW);
		getContentPane().add(pnlContent, BorderLayout.CENTER);
		
		pnlProgress = new JPanel();
		getContentPane().add(pnlProgress, BorderLayout.SOUTH);
		
		switchView(LOGIN_VIEW);
	}

	public void switchView(String screenId) {
		if (LOGIN_VIEW.equals(screenId)) {
			switchToLoginView();
		} else if (MAIN_VIEW.equals(screenId)) {
			switchToMainView();
		}
	}
	
	private void switchToMainView() {
		maximizeScreen();
		switchTitle(MAIN_VIEW);
		switchContent(MAIN_VIEW);
		setTitle(CaptionMessages.MAIN_TITLE);
		remove(pnlTitle);
		refreshGUI();
	}
	
	private void switchToLoginView() {
		restoreScreen();
		switchTitle(LOGIN_VIEW);
		switchContent(LOGIN_VIEW);
		setTitle(CaptionMessages.LOGIN_TITLE);
		refreshGUI();
	}
	
	private void switchTitle(String viewId) {
		switchPanel(pnlTitle, viewId);
	}
	
	private void switchContent(String viewId) {
		switchPanel(pnlContent, viewId);
	}
	
	private void switchPanel(JPanel panel, String viewId) {
		if (panel.getLayout() instanceof CardLayout) {
			CardLayout cardLayout = (CardLayout)panel.getLayout();
			cardLayout.show(panel, viewId);
		}
	}
	
	private static LoginPanel getLoginPanel(AppFrame parent) {
		if (null == loginPanel) {
			loginPanel = new LoginPanel(parent);
		}
		return loginPanel;
	}

	private static MainPanel getMainPanel(AppFrame parent) {
		if (null == mainPanel) {
			mainPanel = new MainPanel(parent);
		}
		return mainPanel;
	}

	static public final String LOGIN_VIEW = "0";
	static public final String MAIN_VIEW = "1";
	private JPanel pnlProgress;

}
